//
//  BRPayRecordDetailVC.m
//  Kexu
//
//  Created by IOS on 2023/7/20.
//

#import "BRPayRecordDetailVC.h"
#import "BRODListView.h"
#import "BRAlertCustomView.h"

@interface BRPayRecordDetailVC ()

@property (nonatomic,strong) BRStackCellView *topStack;

@property (nonatomic,strong) QMUILabel *ruleLabel;

@property (nonatomic,strong) QMUIButton *receiptBtn;

@end

@implementation BRPayRecordDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
    
    /// 计费规则
    self.ruleLabel.text = [[BRUserManager share] br_ruleOfModel:self.dto.billing];
    
    [self br_stackAddSubV];
}

//- (void)br_text:(NSString *)text by:(NSInteger)index {
//    BRODListView *cell = [self.topStack viewWithTag:2000 + index];
//    cell.textL.text = text;
//}

- (void)getReceipt {
    
    BRAlertCustomView *alert = [[BRAlertCustomView alloc] initWithFrame:self.view.bounds type:0];
    alert.titleStr = Localized(@"pay_emailReceiptText");
    alert.titleLB.font = [UIFont fontS:15];
    alert.titleLB.numberOfLines = 0;
    alert.textTF.placeholder = Localized(@"toast_requiredEmail");
    alert.textTF.maximumTextLength = 320;
    alert.textTF.keyboardType = UIKeyboardTypeEmailAddress;
    NSString *emailStr = USERManager.userModel.receiptEmail;
    alert.textTF.text = emailStr.length != 0 ? emailStr : @"";
    [alert setRightBtnTitle:Localized(@"home_confirm")];
    [self.view addSubview:alert];
    WS(weakSelf);
    alert.alertBlock = ^(NSString * _Nonnull changeText, NSInteger index, void (^ _Nonnull hidd)(BOOL)) {
        
        if (changeText.length == 0) {
            [BRHud show:Localized(@"toast_requiredEmail") inView:self.view];
            return;
        }
        if (![BRTools checkEmail:changeText]) {
            [BRHud showAuto:Localized(@"toast_validEmail") inView:self.view];
            return;
        }
        [weakSelf reqestSentToEmail:changeText succ:^(BOOL isSucc) {
            hidd(isSucc);
        }];
        
    };
    
}

- (void)reqestSentToEmail:(NSString *)email succ:(void(^)(BOOL isSucc))statusBlock {
    
    [BRHud showInView:self.view];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"id"] = self.dto.dealId;
    dic[@"orderNo"] = self.dto.orderNo;
    dic[@"receiptEmail"] = email;
    
    [[BRRequestManager shared] POST:[BRAPI receipts] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        statusBlock(YES);
        BRUserModel *model  = USERManager.userModel;
        model.receiptEmail = email;
        USERManager.userModel = model;
        [BRHud hiddenInView:self.view];
        [BRHud showTips:Localized(@"public_success")];

        self.receiptBtn.hidden = YES;
        self.dto.sentReceipt = YES;
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        statusBlock(NO);
        [BRHud hiddenInView:self.view];
    }];
    
}


- (void)br_stackAddSubV {
   
    BOOL hasTax = self.dto.tax > 0;
    if (self.dto.type == 5) {
        hasTax = NO;
    }
    NSString *payAmountText = Localized(@"order_paymentAmount");
    if (hasTax) {
        payAmountText = [NSString stringWithFormat:@"%@ (%@)",payAmountText,Localized(@"pay_includingTax")];
    }
    
    NSString *payTax = [NSString stringWithFormat:@"%@ %.2f%%",Localized(@"pay_tax"),self.dto.tax];
    
    // 默认预付款（押金）5
    NSArray *titles = @[Localized(@"pay_category"),
                        Localized(@"pay_paymentStus"),
                        Localized(@"pay_transactionNo"),
                        Localized(@"order_orderID"),
                        Localized(@"order_paymentMethod"),
                        Localized(@"pay_paymentDate"),
                        Localized(@"pay_refundAmount"),
                        payTax,
                        payAmountText,];
    
    
    NSMutableArray *mutA = [NSMutableArray arrayWithArray:titles];
   
    
    [self.topStack br_addList:mutA];
    
    NSString *payWithStr = @"--";
    if (!BR_StringIsEmpty(self.dto.paymentMethod)) {
        payWithStr = [BRTools payWith:[self.dto.paymentMethod integerValue]];
    }
    
    if ([self.dto.paymentMethod integerValue] <= 1 && ![payWithStr isEqualToString:@"--"]) {
        // 如果是卡支付添加卡后4位显示
        if (self.dto.bankNo.length != 0) {
            payWithStr = [NSString stringWithFormat:@"%@(%@)",payWithStr,self.dto.bankNo];
        }
    }
    NSString *text13 = [BRPayManager br_amount:self.dto.refundAmount];
    BOOL isRefund = self.dto.refund == 1;
    NSString *text1 = [BRTools paymentType:self.dto.type];;
    NSString *text2 =  Localized(@"order_paid");
    if (isRefund) {
        text2 = Localized(@"pay_refuned");
        if (self.dto.paymentState == 3) {
            text2 = Localized(@"payment_partialRefunded");
        }
        if (self.dto.type == 5) {
            text13 = [BRPayManager br_amount:self.dto.amount];
        }
    }

    NSString *text9 = self.dto.transferNo;
    NSString *text10 = payWithStr;
    NSString *text11 = [BRTools getTimeFromTimestamp:self.dto.createTime.integerValue formatter:kTimeFormatter];
    NSString *taxAmount = [BRPayManager br_amount:self.dto.taxAmount];
    NSString *text12 = [BRPayManager br_amount:self.dto.amount];
   
    
    NSString *orderNo = self.dto.orderNo;
    
    NSArray *values = @[text1,text2,text9,orderNo,text10,text11,text13,taxAmount,text12];
    
    for (int i = 0; i < values.count; i++) {
        [self.topStack br_text:values[i] by:i];
    }
    [self.topStack br_hidden:!isRefund by:6];
    
    [self.topStack br_hidden:!hasTax by:7];
    
    [self.topStack br_textFont:[UIFont fontS:20] by:8];
    [self.topStack br_hiddenLine:YES by:titles.count - 1];
}

- (BOOL)isPositive:(NSInteger)type {
    
    if (type %2 == 0) {
        return YES;
    }
    
    return NO;
}


#pragma mark - UI --
- (void)setUI {
    
    self.view.backgroundColor = kColorBGF5;
    
    [self br_createTop:Localized(@"order_paymentDetail")];
    
    //------------------
    UIScrollView *sView = [[UIScrollView alloc] init];
    [self.view addSubview:sView];
    [sView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(kSafeAreaTopHeight);
        make.bottom.offset(0);
    }];
    
    UIView *contView = [[UIView alloc] init];
    contView.backgroundColor = kColorBGF5;
    [sView addSubview:contView];
    [contView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
        make.width.offset(kScreenWidth);
    }];
    
    
    [contView addSubview:self.topStack];
    
    QMUILabel *titleL = [BRToolsView br_label:Localized(@"order_paymentDetail") textColor:kColorTitle font:[UIFont fontS:17]];
    [contView addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.bottom.equalTo(self.topStack.mas_top).offset(-10);
    }];
    
    QMUIButton *receipt = [BRToolsView br_btnBGImg:Localized(@"pay_getReceipt")];
    [self.view addSubview:receipt];
    [receipt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
       
        make.bottom.offset(-(10 + kSafeAreaBottomHeight));
        make.height.mas_equalTo(52);
    }];
    [receipt addTarget:self action:@selector(getReceipt) forControlEvents:UIControlEventTouchUpInside];
    receipt.hidden = (self.dto.type % 2 == 0); //退款不展示
    BOOL isRefund = self.dto.refund == 1;
    if (self.dto.sentReceipt) isRefund = YES;
    receipt.hidden = isRefund;
    self.receiptBtn = receipt;
    /// 流水类型：1-租借 2-租金退款 3-会员 4-会员退款 5-押金 6-押金退款 7-罚金 8-罚金退款 9-添加卡 10-添加卡退款,可用值:1,2,3,4,5,6,7,8,9,10
    NSArray *typs = @[@1,@2,@7,@8];
    if (![typs containsObject:@(self.dto.type)]) {
        [self.topStack mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.offset(14);
            make.right.offset(-14);
            make.top.offset(50);
            make.bottom.offset(-(62 + kSafeAreaBottomHeight));
        }];
        return;
    }else {
        [self.topStack mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.offset(14);
            make.right.offset(-14);
            make.top.offset(50);
        }];
    }
    
    UIView *bottView = [[UIView alloc] init];
    bottView.backgroundColor = UIColor.whiteColor;
    bottView.layer.cornerRadius = 10;
    bottView.layer.masksToBounds = YES;
    [contView addSubview:bottView];
    [bottView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.top.equalTo(self.topStack.mas_bottom).offset(44);
        make.bottom.offset(-(62 + kSafeAreaBottomHeight));
    }];
    
    QMUILabel *billL = [BRToolsView br_label:Localized(@"home_billingRules") textColor:kColorTitle font:[UIFont fontS:17]];
    [contView addSubview:billL];
    [billL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.bottom.equalTo(bottView.mas_top).offset(-10);
    }];
    
    self.ruleLabel = [BRToolsView br_label:@"--" textColor:kColorTitle66B font:[UIFont fontR:13]];
    self.ruleLabel.numberOfLines = 0;
    [bottView addSubview:self.ruleLabel];
    [self.ruleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.top.offset(20);
        make.right.offset(-14);
        make.bottom.offset(-20);
    }];
    
}

- (BRStackCellView *)topStack {
    
    if (_topStack == nil) {
        _topStack = [[BRStackCellView alloc] init];
        _topStack.backgroundColor = UIColor.whiteColor;
        _topStack.layer.cornerRadius = 10;
        _topStack.layer.masksToBounds = YES;
    }
    return _topStack;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
